package com.framework.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.dao.TranOrderDao;
import com.framework.entity.aliPay.AliPayConfig;
import com.framework.entity.flow.FlowAccount;
import com.framework.entity.push.PushConfig;
import com.framework.entity.push.PushContent;
import com.framework.entity.sys.SysAddress;
import com.framework.entity.sys.SysAgent;
import com.framework.entity.ter.TerGoods;
import com.framework.entity.ter.TerTerminalInfo;
import com.framework.entity.tran.TranLogistics;
import com.framework.entity.tran.TranOrder;
import com.framework.exception.RRException;
import com.framework.exception.menu.RespCode;
import com.framework.page.PageUtils;
import com.framework.service.*;
import com.framework.service.agent.AgentIntegralService;
import com.framework.utils.DateUtils;
import com.framework.utils.ali.AliPay;
import com.framework.utils.httpClient.HttpClientUtil;
import com.framework.utils.push.JiGuangPush;
import com.framework.utils.string.StringUtil;
import com.framework.validator.Assert;
import com.framework.view.LogisticsResult;
import com.google.gson.Gson;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wq
 */
@Service("tranOrderService")
public class TranOrderServiceImpl extends ServiceImpl<TranOrderDao, TranOrder> implements TranOrderService {

    @Autowired
    private AgentService agentService;

    @Autowired
    private LogisticsService logisticsService;

    @Autowired
    private AddressService addressService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private FlowAccountService flowAccountService;

    @Autowired
    private TreeAgentService treeAgentService;

    @Autowired
    private PushConfigService pushConfigService;

    @Autowired
    private TerminalInfoService terminalInfoService;

    @Autowired
    private TerTerminalDueService terTerminalDueService;

    @Autowired
    private DistribuService distribuService;

    @Autowired
    private AgentIntegralService agentIntegralService;

    @Autowired
    private IntegralAgentSnService integralAgentSnService;


    @Override
    public List<TranOrder> queryOrdersList(String token, Integer orderState) {
        SysAgent agent = agentService.queryAgentByToken(token);
        List<TranOrder> tranOrders = baseMapper.queryOrdersList(agent.getAgentId(), orderState);
        for (TranOrder tranOrder : tranOrders) {
            switch (tranOrder.getOrderState()) {
                case -1:
                    tranOrder.setStateName("交易关闭");
                    break;
                case 0:
                    tranOrder.setStateName("待付款");
                    break;
                case 1:
                    tranOrder.setStateName("待发货");
                    break;
                case 2:
                    tranOrder.setStateName("待签收");
                    break;
                case 3:
                    tranOrder.setStateName("已完成");
                    break;
                default:
                    tranOrder.setStateName("订单异常");
                    break;
            }
        }

        return tranOrders;
    }

    @Override
    public Map<String, Object> queryLogistics(String token, String orderNo) {
        Map<String, Object> map = new HashedMap();
        if (StringUtils.isBlank(orderNo)) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        //查询订单
        TranOrder order = queryOrdersByNo(orderNo);
        Long logisticsId = order.getLogisticsId();
        if (logisticsId != null) {
            //所属物流
            TranLogistics logistics = logisticsService.queryLogisticsById(logisticsId);
            String code = logistics.getCode();
            String logisticsNum = order.getLogisticsNum();
            //查询物流信息
            String res = HttpClientUtil.doGet("http://www.kuaidi100.com/query", "type=" + code + "&postid=" + logisticsNum);

            Gson gson = new Gson();
            LogisticsResult logisticsResult = gson.fromJson(res, LogisticsResult.class);
            //物流明细
            if ("200".equals(logisticsResult.getStatus())) {
                map.put("logisticsInfo", logisticsResult.getData());
                map.put("logisticsNum", logisticsNum);
                map.put("logisticName", logistics.getLogisticName());
            } else {
                map.put("logisticsInfo", new ArrayList<>());
                map.put("logisticsNum", logisticsNum);
                map.put("logisticName", logistics.getLogisticName());
            }


        } else {
            map.put("logisticsInfo", new ArrayList<>());
            map.put("logistics", "");
            map.put("logisticsNum", "");
        }
        return map;
    }

    @Override
    public TranOrder queryOrdersByNo(String orderNo) {
        Assert.isBlank(orderNo, "订单号不能为空");
        TranOrder order = new TranOrder();
        order.setOrderNo(orderNo);
        TranOrder o = baseMapper.selectOne(order);
        Assert.isNull(o, "未查询到订单");
        return o;
    }

    @Override
    public String addOrder(String token, Long goodsId, Integer goodsNumber, BigDecimal goodsPrice) {
        if (StringUtils.isBlank(token) ||
                goodsId == null ||
                goodsId == 0 ||
                goodsNumber == null ||
                goodsNumber == 0 ||
                goodsPrice == null) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        SysAgent agent = agentService.queryAgentByToken(token);
        Long agentId = agent.getAgentId();
        //查询代理商的默认收货
        SysAddress address = addressService.queryDefaultInfo(agentId);
        if (address == null) {
            throw new RRException(RespCode.NOT_DEFAULT_ADDRESS);
        }
        //查询商品，验证订单的金额
        TerGoods goods = goodsService.selectById(goodsId);
        if (goods == null) {
            throw new RRException("9000", "未查询到商品信息");
        }
        Integer isShow = goods.getIsShow();
        if (isShow == 2) {
            if (!(agent.getDeptId().equals(1L) && goods.getTerminalType().intValue() == 9)) {
                throw new RRException("9000", "商品已经被下架");
            }
        }
        if (!agent.getDeptId().equals(goods.getDeptId())) {
            throw new RRException("9000", "此商品不属于当前登录人");
        }
        Integer leastNum = goods.getLeastNum();
        if (leastNum > goodsNumber) {
            throw new RRException("9000", "购买数量低于设置的值");
        }
        BigDecimal price = goods.getPrice();
        BigDecimal totalPrice = price.multiply(new BigDecimal(goodsNumber));
        int res = totalPrice.compareTo(goodsPrice);
        if (res == 1 || res == -1) {
            throw new RRException("9000", "订单价格不一致");
        }
        //添加预支付订单信息
        String orderNo = StringUtil.getDateString(6);
        insertOrders(orderNo, goodsNumber, goodsPrice, agentId, address.getAddressId(), goodsId);
        return orderNo;
    }

    @Override
    public void cancelOrders(String token, String orderNo) {
        SysAgent sysAgent = agentService.queryAgentByToken(token);
        TranOrder order = queryOrdersByNo(orderNo);
        if (sysAgent.getAgentId().intValue() != order.getAgentId().intValue()) {
            throw new RRException("9000", "订单不属于你，不可取消");
        }
        if (order.getOrderState().intValue() == 0) {
            order.setOrderState(-1);
            baseMapper.updateById(order);
        } else {
            throw new RRException("9000", "订单状态不正确,不可取消");
        }


    }

    @Override
    public void signOrders(String token, String orderNo) {
        SysAgent sysAgent = agentService.queryAgentByToken(token);
        TranOrder order = queryOrdersByNo(orderNo);
        if (sysAgent.getAgentId().intValue() != order.getAgentId().intValue()) {
            throw new RRException("9000", "签收失败,订单不属于你");
        }
        if (order.getOrderState().intValue() == 2) {
            order.setOrderState(3);
            baseMapper.updateById(order);
        } else {
            throw new RRException("9000", "签收失败,订单状态不正确");
        }

    }

    @Override
    public void insertOrders(String orderNo, Integer goodsNumber, BigDecimal goodsPrice, Long agentId, String addressId, Long goodsId) {

       /* Integer maxOrderId = orderTypeService.getMaxOrderId();
        OrderType orderType=new OrderType();
        maxOrderId++;
        orderType.setOrderId(maxOrderId);
        orderType.setOrderNo(orderNo);
        orderType.setState(2);
        orderTypeService.insert(orderType);*/

        TranOrder orders = new TranOrder();
        //orders.setOrderId(Long.valueOf(maxOrderId));

        orders.setAgentId(agentId);
        orders.setByDate(new Date());
        orders.setCreateTime(new Date());
        orders.setGoodsId(goodsId);
        orders.setGoodsPrice(goodsPrice);
        orders.setGoodsNumber(goodsNumber);
        orders.setAddressId(addressId);
        orders.setOrderNo(orderNo);
        baseMapper.insert(orders);

    }

    @Override
    public Map<String, Object> queryOrderInfo(String orderNo) {

        Map<String, Object> map = new HashMap<>(3);
        TranOrder orders = queryOrdersByNo(orderNo);
        //商品id
        Long goodsId = orders.getGoodsId();
        //地址id
        String addressId = orders.getAddressId();
        if (StringUtils.isNotBlank(addressId)) {
            SysAddress address = addressService.queryAddressById(addressId);
            map.put("address", address);
        }
        TerGoods goods = goodsService.selectById(goodsId);
        orders.setCoverImg(goods.getCoverImg());
        orders.setPrice(goods.getPrice());
        orders.setGoodsName(goods.getName());
        map.put("orders", orders);
        return map;
    }

    @Override
    public Integer queryByTerminalCount(Long agentId, Integer type, int isOwn) {
        return baseMapper.queryTeamBuyTerCount(agentId, type, isOwn);
    }

    @Override
    public void deleteOrder(String token, String orderNo) {
        SysAgent sysAgent = agentService.queryAgentByToken(token);
        TranOrder order = queryOrdersByNo(orderNo);
        if (sysAgent.getAgentId().intValue() != order.getAgentId().intValue()) {
            throw new RRException("9000", "无法删除,该订单不属于你");
        }

        if (order.getOrderState().intValue() == -1) {
            deleteById(order.getOrderId());
        } else {
            throw new RRException("9000", "删除失败,订单状态不正确");
        }
    }

    @Override
    public String pay(String token, String orderNo, Integer payType, String password) {
        if (StringUtils.isBlank(token) ||

                StringUtils.isBlank(orderNo)) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        SysAgent agent = agentService.queryAgentByToken(token);
        Long agId = agent.getAgentId();
        //渠道id
        Long deptId = agent.getDeptId();
        //查询渠道支付宝参数信息
        AliPayConfig aliPayConfig = queryAliPayConfig(deptId);
        if (aliPayConfig == null) {
            throw new RRException("9000", "未查询到设置的支付宝参数");
        }
        TranOrder order = queryOrdersByNo(orderNo);
        Assert.isBlank(orderNo, "未查询到订单");
        BigDecimal goodsPrice = order.getGoodsPrice();
        Long agentId = order.getAgentId();
        if (agentId.intValue() != agId.intValue()) {
            throw new RRException("9000", "此订单不属于当前登录人");
        }
        //校验订单状态、支付状态
        Integer payState = order.getOrderState();
        if (payState.intValue() != 0) {
            throw new RRException("9000", "支付状态不正确");
        }
        Long goodsId = order.getGoodsId();
        TerGoods terGoods = goodsService.selectById(goodsId);
        String orderString;
        //支付方式 1：支付宝
        //防止以后出现多种支付方式
        switch (payType) {
            case 1:
                Map<String, Object> map = new HashMap<>();
                map.put("body", terGoods.getName());
                map.put("subject", terGoods.getName());
                map.put("order_no", orderNo);
                map.put("amount", goodsPrice);

                try {
                    orderString = AliPay.Pay(map, aliPayConfig);
                } catch (Exception e) {
                    throw new RRException("9000", "支付失败，" + e.getMessage());
                }
                if (StringUtils.isBlank(orderString)) {
                    throw new RRException("9000", "启用支付宝接口失败");
                }
                break;
            default:
                throw new RRException("9000", "支付类型错误");
        }
        return orderString;
    }

    @Override
    public void successPayState(String orderNo, String aliPayType) {


        TranOrder tranOrder = queryOrdersByNo(orderNo);

        if(tranOrder.getOrderState().intValue()>=1){
            return;
        }

        tranOrder.setPayType(aliPayType);
        tranOrder.setOrderState(1);
        boolean b = updateById(tranOrder);
        TranOrder orders = tranOrder;
        if (b) {
            //添加账户流水日志
            FlowAccount account = new FlowAccount();
            account.setBelId(orders.getOrderNo());
            FlowAccount temp = flowAccountService.queryByBelId(account);
            if (temp == null) {
                account.setAccountType(2);
                account.setAmount(orders.getGoodsPrice());
                account.setAgentId(orders.getAgentId());
                account.setSupportType(1);
                flowAccountService.insertFlowAccount(account);
            }
            //回调后购买成功推送
            pushMessage(orders);
            //如果采购大于等于300则另设等级
            if (orders.getGoodsNumber().intValue() >= 300) {
                agentService.updateAgentGrade(orders.getAgentId());
            }
        }
    }

    @Override
    public void pushMessage(TranOrder order) {
        Long agentId = order.getAgentId();
        SysAgent agent = agentService.queryAgentById(agentId);
        //没有查到合伙人则不推送
        if (agent == null) {
            return;
        }
        TerGoods goods = goodsService.queryGoodsById(order.getGoodsId());
        SysAgent base = agentService.queryBasicAgentBydeptId(agent.getDeptId());
        //查询除平台外的其余上级
        List<Long> list = treeAgentService.queryPidList(order.getAgentId(), base.getAgentId());
        List<String> strings = list.stream().map(e -> e.toString()).collect(Collectors.toList());
        if (list.size() > 0) {
            PushConfig pushconfig = pushConfigService.queryPushConfigByDeptId(agent.getDeptId());
            if (pushconfig != null) {
                String[] strs = list.toArray(new String[strings.size()]);
                String str = "您的下属合伙人" + agent.getName() +
                        "购买了" + order.getGoodsNumber() + "台"
                        + goods.getName();
                //配置推送内容
                PushContent pushContent = new PushContent();
                pushContent.setPushType("alias");
                pushContent.setAssType(2);
                pushContent.setNoticeType("ass");
                pushContent.setAlert(str);
                pushContent.setTitle("机具购入");
                pushContent.setAlias(strs);
                //推送
                JiGuangPush.jiguangPush(pushContent, pushconfig);

            }

        }

    }

    @Override
    public PageUtils queryList(Map<String, Object> params) {
        if ("".equals(params.get("byDate"))) {
            params.put("byDate", null);
        }
        int curPage = Integer.valueOf(params.get("page").toString());
        int size = Integer.valueOf(params.get("limit").toString());
        params.put("start", (curPage - 1) * size);
        params.put("limit", size);
        List<Map<String, Object>> list = baseMapper.queryList(params);
        for (Map<String, Object> map : list) {
            Integer orderState = (Integer) map.get("orderState");
            switch (orderState) {
                case 0:
                    map.put("orderState", "待付款");
                    break;
                case 1:
                    map.put("orderState", "待发货");
                    break;
                case 2:
                    map.put("orderState", "待签收");
                    break;
                case 3:
                    map.put("orderState", "已完成");
                    break;
                case -1:
                    map.put("orderState", "交易关闭");
                    break;
                default:
                    map.put("orderState", "订单异常");
                    break;
            }

        }

        Integer totalCount = baseMapper.queryCount(params);
        return new PageUtils(list, totalCount, size, curPage);
    }

    @Override
    public void handleOrder(Map<String, Object> params) {
        if (params == null) {
            throw new RRException("9000", "参数不能为空");
        }
        //获取开始终端的数组
        List<String> startArray = (List<String>) params.get("startArray");
        //结束数组
        List<String> endArray = (List<String>) params.get("endArray");
        //单个的数组
        List<String> aloneArray = (List<String>) params.get("aloneArray");
        //划拨目标人
        Long agentId = Long.valueOf(params.get("agentId").toString());
        //是否线上
        Long isOnline = Long.valueOf(params.get("isOnline").toString());
        //订单id
        Long orderId = Long.valueOf(params.get("orderId").toString());

        Long deptId = Long.valueOf(params.get("deptId").toString());

        Integer terminalType= Integer.valueOf(params.get("terminalType").toString());

        List<TerTerminalInfo> integralTerminalList=null;
        boolean integralFlag=terminalType.intValue()==9;
        if(integralFlag){
            integralTerminalList=new ArrayList<>();
        }

        BigDecimal reapAmount = null;
        if (params.get("reapAmount") != null) {
            reapAmount = new BigDecimal(params.get("reapAmount").toString());
        }
        Date dueDate = null;
        if (params.get("dueDate") != null) {
            dueDate = DateUtils.stringToDate(params.get("dueDate").toString(), DateUtils.DATE_PATTERN);
        }
        BigDecimal afterCash = null;
        if (params.get("afterCash") != null) {
            afterCash = new BigDecimal(params.get("afterCash").toString());
        }
        List<TerTerminalInfo> tempList;
        //查询条件
        Map<String, Object> newParams = new HashMap<>();
        newParams.put("terminalType", params.get("terminalType"));
        newParams.put("deptId", deptId);
        Integer totalCount = 0;
        //查出订单以作修改
        TranOrder order = baseMapper.selectById((Serializable) params.get("orderId"));
        if (order == null) {
            throw new RRException("9000", "未查询到订单");
        }
        if (startArray != null) {
            //处理区间里的机器
            if (startArray.size() > 0) {
                for (int i = 0; i < startArray.size(); i++) {
                    newParams.put("startNo", startArray.get(i));
                    newParams.put("endNo", endArray.get(i));
                    //根据终端号查出列表
                    tempList = terminalInfoService.queryTerListByNo(newParams);
                    if(integralFlag){
                        integralTerminalList.addAll(tempList);
                    }
                    totalCount += tempList.size();
                    terTerminalDueService.addTerminalDueList(tempList, isOnline, reapAmount, dueDate, afterCash, deptId);
                    terminalInfoService.handleTer(tempList, agentId, reapAmount, isOnline, startArray.get(i), endArray.get(i), orderId, deptId, null);
                    distribuService.handleDistribu(tempList, agentId, deptId);
                }
            }
        }

        if (aloneArray != null) {
            //单个机器
            if (aloneArray.size() > 0) {
                for (String str : aloneArray) {
                    newParams.put("aloneNo", str);
                    tempList = terminalInfoService.queryTerListByNo(newParams);
                    if(integralFlag){
                        integralTerminalList.addAll(tempList);
                    }
                    totalCount += tempList.size();
                    terTerminalDueService.addTerminalDueList(tempList, isOnline, reapAmount, dueDate, afterCash, deptId);
                    terminalInfoService.handleTer(tempList, agentId, reapAmount, isOnline, str, str, orderId, deptId, null);
                    distribuService.handleDistribu(tempList, agentId, deptId);
                }
            }
        }
        if (startArray != null || startArray != null) {
            if (order.getGoodsNumber().intValue() != totalCount.intValue()) {
                throw new RRException("9000", "分配的机具数量与订单不符");
            }
        }

        //订单状态更改为待签收
        order.setOrderState(2);
        //物流信息填写则添加
        if (params.get("logisticId") != null && !"".equals(params.get("logisticId"))) {

            order.setLogisticsId(Long.valueOf(params.get("logisticId").toString()));
        }
        if (params.get("logisticCode") != null && !"".equals(params.get("logisticCode"))) {

            order.setLogisticsNum(params.get("logisticCode").toString());
        }
        baseMapper.updateById(order);

        if(integralFlag){
            integralAgentSnService.addRecord(agentId,integralTerminalList);
        }

    }

    @Override
    public SysAddress queryAddressByOrderId(String orderId) {
        return baseMapper.queryAddressByOrderId(orderId);
    }

    @Override
    public Map<String, Object> queryNoticeDetail(Long orderId) {
        Map<String, Object> result = new HashMap<>();

        List<Map<String, Object>> list = this.baseMapper.queryNoticeDetail(orderId);
        TranOrder order = baseMapper.selectById(orderId);
        //有详情则查询相关情况
        if (list != null && list.size() > 0) {
            Long disAgentId = Long.valueOf(list.get(0).get("disAgentId").toString());
            SysAgent disSysAgent = agentService.queryAgentById(disAgentId);
            Long acceptAgentId = Long.valueOf(list.get(0).get("acceptAgentId").toString());
            SysAgent acceptSysAgent = agentService.queryAgentById(acceptAgentId);
            result.put("disSysAgent", disSysAgent);
            result.put("acceptSysAgent", acceptSysAgent);
        } else {
            Long agentId = order.getAgentId();
            SysAgent acceptSysAgent = agentService.queryAgentById(agentId);
            result.put("disSysAgent", agentService.queryBasicAgentBydeptId(acceptSysAgent.getDeptId()));
            result.put("acceptSysAgent", acceptSysAgent);
        }

        result.put("list", list);

        if (order != null) {
            String logisticsNum = order.getLogisticsNum();
            TranLogistics l = logisticsService.selectById(order.getLogisticsId());
            if (l != null) {
                String logisticsName = l.getLogisticName();
                result.put("logisticsNum", logisticsNum);
                result.put("logisticsName", logisticsName);
            } else {
                result.put("logisticsNum", "无物流单号");
                result.put("logisticsName", "无快递公司");
            }
        }

        return result;
    }

    @Override
    public AliPayConfig queryAliPayConfig(Long deptId) {
        return baseMapper.queryAliPayConfig(deptId);
    }


    @Override
    public List<Map<String, Object>> queryOrderListByAgentIdAndGoodsId(Long agentId, Long goodsId) {
        return baseMapper.queryOrderListByAgentIdAndGoodsId(agentId, goodsId);
    }

    @Override
    public void payByIntegral(String token, Long goodsId, Integer totalIntegral, Integer goodsNum) {
        SysAgent agent = agentService.queryAgentByToken(token);
        //扣除积分病生成流水
        agentIntegralService.redIntegralByPay(agent.getAgentId(), totalIntegral, goodsId, goodsNum);

        //生成订单
        TranOrder orders = new TranOrder();
        String orderNo = StringUtil.getDateString(6);
        orders.setAgentId(agent.getAgentId());
        orders.setByDate(new Date());
        orders.setCreateTime(new Date());
        orders.setGoodsId(goodsId);
        orders.setGoodsPrice(new BigDecimal(totalIntegral.toString()));
        orders.setGoodsNumber(goodsNum);
        orders.setOrderNo(orderNo);
        orders.setPayType("byIntegral");
        orders.setOrderState(1);
        baseMapper.insert(orders);


    }

    @Override
    public List<TranOrder> getIntegralOrders(String token, Integer orderState) {
        SysAgent agent = agentService.queryAgentByToken(token);

        List<TranOrder> integralOrders = baseMapper.getIntegralOrders(agent.getAgentId(), orderState);
        for (TranOrder tranOrder : integralOrders) {
            switch (tranOrder.getOrderState()) {
                case -1:
                    tranOrder.setStateName("交易关闭");
                    break;
                case 0:
                    tranOrder.setStateName("待付款");
                    break;
                case 1:
                    tranOrder.setStateName("待发货");
                    break;
                case 2:
                    tranOrder.setStateName("待签收");
                    break;
                case 3:
                    tranOrder.setStateName("已完成");
                    break;
                default:
                    tranOrder.setStateName("订单异常");
                    break;
            }
        }
        return integralOrders;
    }



}
